iT邦幫忙

2023 iThome 鐵人賽

DAY 24
0

昨天提到,目前已有許多測試工具支援視覺回歸測試,今天會詳細介紹如何使用其中一種測試工具,也就是 Day20 提到的 Cypress Plugin Snapshots

如官方文件說明安裝完後:npm install cypress-plugin-snapshots --save-dev,依據 Cypress 版本,設定方式不同:

Cypress 6.0.0 以前的版本

1.於 cypress.json 寫入

"ignoreTestFiles": [
  "**/__snapshots__/*",
  "**/__image_snapshots__/*"
]

2.於 cypress/plugins/index.js 寫入

const { initPlugin } = require('cypress-plugin-snapshots/plugin');

module.exports = (on, config) => {
  initPlugin(on, config);
  return config;
};

3.於 cypress/support/index.js 寫入

import 'cypress-plugin-snapshots/commands';

4.再於 cypress.json 中加入

"env": {
	"cypress-plugin-snapshots": {
		"imageConfig": {
			"threshold": 0.01
		}
	}
  }

5.即可開始撰寫 screen-shoots 的方法

ex.

describe('template spec', () => {
  it('passes', () => {
    cy.visit('http://127.0.0.1:5500/index.html')
	.then(() => {
        cy.get('button').toMatchSnapshot();
    });
  })
})

6.0.0 之後的版本

1.於 cypress.config.js 中寫進

excludeSpecPattern: [        // this is "ignoreTestFiles" in Cypress v9
      "**/__snapshots__/*",
      "**/__image_snapshots__/*" 
    ],
    "env": {      // just pasted everything from the docs here
      "cypress-plugin-snapshots": {
        "autoCleanUp": false,            // Automatically remove snapshots that are not used by test
        "autopassNewSnapshots": true,    // Automatically save & pass new/non-existing snapshots
        "diffLines": 3,                  // How many lines to include in the diff modal
        "excludeFields": [],             // Array of fieldnames that should be excluded from snapshot
        "ignoreExtraArrayItems": false,  // Ignore if there are extra array items in result
        "ignoreExtraFields": false,      // Ignore extra fields that are not in `snapshot`
        "normalizeJson": true,           // Alphabetically sort keys in JSON
        "prettier": true,                // Enable `prettier` for formatting HTML before comparison
        "imageConfig": {
          "createDiffImage": true,       // Should a "diff image" be created, can be disabled for performance
          "resizeDevicePixelRatio": true,// Resize image to base resolution when Cypress is running on high DPI screen, `cypress run` always runs on base resolution
          "threshold": 0.01,             // Amount in pixels or percentage before snapshot image is invalid
          "thresholdType": "percent"     // Can be either "pixels" or "percent"
        },
        "screenshotConfig": {            // See https://docs.cypress.io/api/commands/screenshot.html#Arguments
          "blackout": [],
          "capture": "fullPage",
          "clip": null,
          "disableTimersAndAnimations": true,
          "log": false,
          "scale": false,
          "timeout": 30000
        },
        "serverEnabled": true,           // Enable "update snapshot" server and button in diff modal
        "serverHost": "localhost",       // Hostname for "update snapshot server"
        "serverPort": 2121,              // Port number for  "update snapshot server"
        "updateSnapshots": false,        // Automatically update snapshots, useful if you have lots of changes
        "backgroundBlend": "difference"  // background-blend-mode for diff image, useful to switch to "overlay"
      }
    }

2.於 support/command.js 中載入

import 'cypress-plugin-snapshots/commands';

3.即可開始撰寫測試

describe('template spec', () => {
  it('passes', () => {
    cy.visit('http://127.0.0.1:5500/index.html')
	.then(() => {
        cy.get('button').toMatchSnapshot();
    });
  })
})

設定 Baseline、執行測試並比較結果

1.當初次跑測試時,會建立一個 Baseline 的檔案,放置於__snapshots__底下(ex. snapshots/spec.cy.js.snap)

2.接下來每次跑,就會以上述檔案作為 Baseline 去衡量,若成功,畫面上會出現「SNAPSHOTS MATCH」

https://ithelp.ithome.com.tw/upload/images/20231008/20161783ggULZDd6Sm.png

點開後,可看到 Baseline 的 HTML code

https://ithelp.ithome.com.tw/upload/images/20231008/20161783gAbgK8uDvT.png

3.若畫面不一致時,可看到失敗訊息 COMPARE SNAPSHOTS ERROR,點開可看到兩者差異

https://ithelp.ithome.com.tw/upload/images/20231008/20161783RDsD2PxTCi.png

4.並可以按「Update snapshots」,來更新「新的 Baseline」,那麼下次就會以新的作為參考

https://ithelp.ithome.com.tw/upload/images/20231008/20161783OvLl4bn6Ke.png


上一篇
[Day 23] 視覺回歸測試(ㄧ)- 簡介
下一篇
[Day 25] 視覺回歸測試(三)- Percy
系列文
手動測試好累喔!一起來寫前端自動化測試吧~30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言